package com.example.myapplication;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

/**
 * 我的 Fragment
 * 显示用户信息、兴趣，提供选择兴趣和退出登录功能
 */
public class ProfileFragment extends Fragment {
    private static final String ARG_USERNAME = "username";
    private static final String ARG_EMAIL = "email";
    private static final String ARG_INTEREST = "interest";
    
    private ImageView ivAvatar;
    private TextView tvUsername;
    private TextView tvInterest;
    private Button btnSelectInterest;
    private Button btnPresetAvatar;
    private Button btnUseProjectImage;
    private Button btnMyBooks;
    private Button btnResetAvatar;
    private Button btnLogout;
    
    private String username;
    private String email;
    private String interest = "未选择";
    private ActivityResultLauncher<Intent> interestLauncher;
    private ActivityResultLauncher<Intent> imagePickerLauncher;
    private ActivityResultLauncher<String> permissionLauncher;
    
    private AvatarManager avatarManager;

    public static ProfileFragment newInstance(String username, String email, String interest) {
        ProfileFragment fragment = new ProfileFragment();
        Bundle args = new Bundle();
        args.putString(ARG_USERNAME, username);
        args.putString(ARG_EMAIL, email);
        args.putString(ARG_INTEREST, interest);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if (getArguments() != null) {
            username = getArguments().getString(ARG_USERNAME, "");
            email = getArguments().getString(ARG_EMAIL, "");
            interest = getArguments().getString(ARG_INTEREST, "未选择");
        }
        
        // 恢复保存的状态
        if (savedInstanceState != null) {
            username = savedInstanceState.getString(ARG_USERNAME, "");
            email = savedInstanceState.getString(ARG_EMAIL, "");
            interest = savedInstanceState.getString(ARG_INTEREST, "未选择");
        }
        
        // 初始化头像管理器
        avatarManager = new AvatarManager(requireContext());
        
        // 注册兴趣选择回调
        interestLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == getActivity().RESULT_OK) {
                            Intent data = result.getData();
                            if (data != null) {
                                String selectedInterest = data.getStringExtra("select_interest");
                                updateInterest(selectedInterest);
                                
                                // 通知 HomeActivity 更新兴趣
                                if (getActivity() instanceof HomeActivity) {
                                    ((HomeActivity) getActivity()).onInterestUpdated(selectedInterest);
                                }
                            }
                        }
                    }
                }
        );
        
        // 注册图片选择回调
        imagePickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        android.util.Log.d("ProfileFragment", "图片选择回调被触发，resultCode=" + result.getResultCode());
                        
                        if (result.getResultCode() == getActivity().RESULT_OK) {
                            Intent data = result.getData();
                            if (data != null && data.getData() != null) {
                                Uri imageUri = data.getData();
                                android.util.Log.d("ProfileFragment", "获取到图片URI: " + imageUri.toString());
                                handleImageSelected(imageUri);
                            } else {
                                android.util.Log.w("ProfileFragment", "未获取到图片URI");
                                Toast.makeText(getContext(), "未选择图片", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            android.util.Log.d("ProfileFragment", "用户取消了选择");
                        }
                    }
                }
        );
        
        // 注册权限请求回调
        permissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                new ActivityResultCallback<Boolean>() {
                    @Override
                    public void onActivityResult(Boolean isGranted) {
                        if (isGranted) {
                            // 权限已授予，打开相册
                            openImagePicker();
                        } else {
                            // 权限被拒绝，显示友好提示
                            showPermissionDeniedDialog();
                        }
                    }
                }
        );
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        
        ivAvatar = view.findViewById(R.id.iv_avatar);
        tvUsername = view.findViewById(R.id.tv_username);
        tvInterest = view.findViewById(R.id.tv_interest);
        btnSelectInterest = view.findViewById(R.id.btn_select_interest);
        btnPresetAvatar = view.findViewById(R.id.btn_preset_avatar);
        btnUseProjectImage = view.findViewById(R.id.btn_use_project_image);
        btnMyBooks = view.findViewById(R.id.btn_my_books);
        btnResetAvatar = view.findViewById(R.id.btn_reset_avatar);
        btnLogout = view.findViewById(R.id.btn_logout);
        
        // 显示用户名和兴趣
        tvUsername.setText("用户名：" + username);
        tvInterest.setText("当前兴趣：" + interest);
        
        // 加载用户头像
        loadAvatar();
        
        // 头像点击事件
        ivAvatar.setOnClickListener(v -> {
            android.util.Log.d("ProfileFragment", "头像被点击");
            checkPermissionAndPickImage();
        });
        
        // 选择兴趣按钮
        btnSelectInterest.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), InterestActivity.class);
            interestLauncher.launch(intent);
        });
        
        // 预设头像按钮
        btnPresetAvatar.setOnClickListener(v -> showPresetAvatarDialog());
        
        // 使用项目图片按钮
        btnUseProjectImage.setOnClickListener(v -> useProjectImage());
        
        // 我的书籍按钮
        btnMyBooks.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), BookManagementActivity.class);
            intent.putExtra("user_email", email);
            startActivity(intent);
        });
        
        // 恢复默认头像按钮
        btnResetAvatar.setOnClickListener(v -> showResetAvatarDialog());
        
        // 退出登录按钮
        btnLogout.setOnClickListener(v -> showLogoutDialog());
        
        return view;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(ARG_USERNAME, username);
        outState.putString(ARG_EMAIL, email);
        outState.putString(ARG_INTEREST, interest);
    }

    /**
     * 加载用户头像
     */
    private void loadAvatar() {
        if (email == null || email.isEmpty()) {
            return;
        }
        
        // 使用邮箱作为用户唯一标识
        Bitmap avatarBitmap = avatarManager.loadAvatar(email);
        if (avatarBitmap != null) {
            ivAvatar.setImageBitmap(avatarBitmap);
        } else {
            // 显示默认头像
            ivAvatar.setImageResource(R.mipmap.ic_launcher);
        }
    }

    /**
     * 检查权限并选择图片
     */
    private void checkPermissionAndPickImage() {
        String permission = getRequiredPermission();
        
        // Android 10-12 使用 Scoped Storage，无需权限
        if (permission == null) {
            android.util.Log.d("ProfileFragment", "Android 10-12, 无需权限，直接打开选择器");
            openImagePicker();
            return;
        }
        
        // 检查权限
        if (ContextCompat.checkSelfPermission(requireContext(), permission) == PackageManager.PERMISSION_GRANTED) {
            android.util.Log.d("ProfileFragment", "权限已授予，打开选择器");
            openImagePicker();
        } else {
            android.util.Log.d("ProfileFragment", "权限未授予，显示权限说明对话框");
            // 首次请求权限，显示说明对话框
            showPermissionRationaleDialog(permission);
        }
    }

    /**
     * 获取所需权限（根据 Android 版本）
     */
    private String getRequiredPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // Android 13+
            return Manifest.permission.READ_MEDIA_IMAGES;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // Android 10-12
            return null; // 使用 Scoped Storage，无需权限
        } else { // Android 9 及以下
            return Manifest.permission.READ_EXTERNAL_STORAGE;
        }
    }

    /**
     * 显示权限说明对话框
     */
    private void showPermissionRationaleDialog(String permission) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("需要存储权限");
        builder.setMessage("为了让您选择相册中的图片作为头像，需要授予存储权限。");
        builder.setPositiveButton("授予权限", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                permissionLauncher.launch(permission);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getContext(), "未授予权限，无法选择图片", Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();
    }

    /**
     * 显示权限被拒绝对话框
     */
    private void showPermissionDeniedDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("权限被拒绝");
        builder.setMessage("您已拒绝存储权限，无法选择图片。如需使用此功能，请前往设置手动授予权限。");
        builder.setPositiveButton("前往设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", requireContext().getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 打开图片选择器（支持相册和文件管理器）
     */
    private void openImagePicker() {
        try {
            android.util.Log.d("ProfileFragment", "开始打开图片选择器");
            
            // 使用 ACTION_GET_CONTENT 支持从文件管理器选择
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            
            // 创建选择器，同时支持相册和文件管理器
            Intent chooserIntent = Intent.createChooser(intent, "选择图片来源");
            
            android.util.Log.d("ProfileFragment", "启动图片选择器");
            imagePickerLauncher.launch(chooserIntent);
            
        } catch (Exception e) {
            android.util.Log.e("ProfileFragment", "打开图片选择器失败", e);
            Toast.makeText(getContext(), "打开图片选择器失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 处理选择的图片
     */
    private void handleImageSelected(Uri imageUri) {
        if (email == null || email.isEmpty()) {
            Toast.makeText(getContext(), "用户信息异常", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 保存头像
        boolean success = avatarManager.saveAvatar(email, imageUri);
        
        if (success) {
            // 重新加载头像
            loadAvatar();
            Toast.makeText(getContext(), "头像更换成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getContext(), "头像保存失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 使用项目中的图片 (lx.png)
     */
    private void useProjectImage() {
        try {
            // 加载 drawable 中的 lx.png
            android.graphics.drawable.Drawable drawable = ContextCompat.getDrawable(requireContext(), R.drawable.lx);
            if (drawable == null) {
                Toast.makeText(getContext(), "加载项目图片失败", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 将 Drawable 转为 Bitmap
            android.graphics.Bitmap bitmap = android.graphics.Bitmap.createBitmap(
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                android.graphics.Bitmap.Config.ARGB_8888
            );
            android.graphics.Canvas canvas = new android.graphics.Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            
            // 删除旧头像
            avatarManager.deleteAvatar(email);
            
            // 保存新头像
            java.io.File avatarDir = new java.io.File(requireContext().getFilesDir(), "avatars");
            if (!avatarDir.exists()) {
                avatarDir.mkdirs();
            }
            
            java.io.File avatarFile = new java.io.File(avatarDir, "avatar_" + email + ".jpg");
            java.io.FileOutputStream outputStream = new java.io.FileOutputStream(avatarFile);
            bitmap.compress(android.graphics.Bitmap.CompressFormat.JPEG, 90, outputStream);
            outputStream.flush();
            outputStream.close();
            bitmap.recycle();
            
            // 重新加载头像
            loadAvatar();
            Toast.makeText(getContext(), "已使用项目图片 lx.png", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            android.util.Log.e("ProfileFragment", "使用项目图片失败", e);
            Toast.makeText(getContext(), "设置失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示预设头像选择对话框
     */
    private void showPresetAvatarDialog() {
        // 预设头像选项（使用系统内置图标）
        final int[] presetAvatars = {
            android.R.drawable.sym_def_app_icon,
            android.R.drawable.ic_menu_gallery,
            android.R.drawable.ic_menu_camera,
            android.R.drawable.ic_menu_myplaces,
            android.R.drawable.ic_menu_compass,
            android.R.drawable.ic_menu_preferences
        };
        
        final String[] avatarNames = {
            "📱 默认图标",
            "🖼️ 图库图标",
            "📷 相机图标",
            "📍 地点图标",
            "🧭 指南针图标",
            "⚙️ 设置图标"
        };
        
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("选择预设头像");
        builder.setItems(avatarNames, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 将选中的系统图标转为 Bitmap 并保存
                savePresetAvatar(presetAvatars[which]);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 保存预设头像
     */
    private void savePresetAvatar(int drawableId) {
        try {
            // 将 Drawable 转为 Bitmap
            android.graphics.drawable.Drawable drawable = ContextCompat.getDrawable(requireContext(), drawableId);
            if (drawable == null) {
                Toast.makeText(getContext(), "加载头像失败", Toast.LENGTH_SHORT).show();
                return;
            }
            
            android.graphics.Bitmap bitmap = android.graphics.Bitmap.createBitmap(
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                android.graphics.Bitmap.Config.ARGB_8888
            );
            android.graphics.Canvas canvas = new android.graphics.Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            
            // 删除旧头像
            avatarManager.deleteAvatar(email);
            
            // 保存新头像
            java.io.File avatarDir = new java.io.File(requireContext().getFilesDir(), "avatars");
            if (!avatarDir.exists()) {
                avatarDir.mkdirs();
            }
            
            java.io.File avatarFile = new java.io.File(avatarDir, "avatar_" + email + ".jpg");
            java.io.FileOutputStream outputStream = new java.io.FileOutputStream(avatarFile);
            bitmap.compress(android.graphics.Bitmap.CompressFormat.JPEG, 90, outputStream);
            outputStream.flush();
            outputStream.close();
            bitmap.recycle();
            
            // 重新加载头像
            loadAvatar();
            Toast.makeText(getContext(), "头像设置成功", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Toast.makeText(getContext(), "设置失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示恢复默认头像对话框
     */
    private void showResetAvatarDialog() {
        if (!avatarManager.hasAvatar(email)) {
            Toast.makeText(getContext(), "当前已是默认头像", Toast.LENGTH_SHORT).show();
            return;
        }
        
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("恢复默认头像");
        builder.setMessage("确认要删除自定义头像并恢复为默认头像吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                boolean success = avatarManager.deleteAvatar(email);
                if (success) {
                    loadAvatar();
                    Toast.makeText(getContext(), "已恢复默认头像", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getContext(), "操作失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 更新兴趣数据
     */
    public void updateInterest(String newInterest) {
        this.interest = newInterest;
        if (tvInterest != null) {
            tvInterest.setText("当前兴趣：" + newInterest);
        }
    }

    /**
     * 显示退出登录对话框
     */
    private void showLogoutDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("退出登录");
        builder.setMessage("确认要退出登录吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 返回登录页面
                Intent intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);
                getActivity().finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }
}
